var Menu = function (obj,pid,leven) {
    var data = [];
    var menu = $("<li><a href='#'><i></i></a></li>");
    var childMenu = $("<ul class=\"nav nav-third-level\">");

    var search = function (pid) {
        var where = null;
        var callback = function (result) {
            if (result.result == "success") {
                data = result.data;
                init(obj,leven);
            }
        };
        if(pid){
            where = $("<div><input name='parentMenu' value='"+pid+"'/></div>");
        }else{
            where = callback;
        }
        CustomForm.search("menu",where,callback);
    }

    var init = function(obj,leven){
        leven=leven?leven:1;
        if(leven==1){
            childMenu = $("<ul class=\"nav\" id=\"main-menu\">");
        }else if(leven==2){
            childMenu = $("<ul class=\"nav nav-second-level\">");
        }else if(leven==3){
            childMenu = $("<ul class=\"nav nav-third-level\">");
        }

        for (var i = 0;i<data.length;i++){
            var _menu = menu.clone();
            _menu.find("a").attr("data-url",data[i].menuAction);
            _menu.attr("data-name",data[i].menuName);
            _menu.attr("data-remark",data[i].menuRemark);
            _menu.find("a").append(data[i].menuName);
            _menu.find("i").addClass(data[i].menuIcon);
            if(data[i].parentMenu){
                new Menu(_menu.find("li"),data[i].parentMenu,leven+1);
            }
            childMenu.append(_menu);
            obj.append(childMenu);
        }
        bindEvent(obj);
    }

    var bindEvent = function (obj) {
        $(obj).on("click","li",function (e) {
            var url = $(this).find("a").data("url");
            $("#ifream").load(url);
            var name = $(this).data("name");
            var remark = $(this).data("remark");
            $(".page-header").html(name+" <small> "+remark+" </small>");
        })
    }

    var setData = function (d) {
        data = d;
    }
    search(pid);
}